package dbms.query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import dbms.Debug;
import dbms.metadata.TableManager;

public class ProductPlan extends Plan {

	/*public TablePlan tablePlanA;
	public TablePlan tablePlanB;
	
	public ProductPlan next;
	
	public ProductPlan (TablePlan tablePlan, ProductPlan next) {
		this.tablePlanA = tablePlan;
		this.next = next;
	}
	
	public ProductPlan (TablePlan tablePlanA, TablePlan tablePlanB) {
		this.tablePlanA = tablePlanA;
		this.tablePlanB = tablePlanB;
	}*/

	public ProductPlan() {
	}

	public ResultSet execute(ResultSet resultA, ResultSet resultB) {
		int numberA = resultA.resultNumber;
		int numberB = resultB.resultNumber;
		Map<String, List<Object>> resultSet = new HashMap<String, List<Object>>();
		String tableNameA = resultA.resultName;
		String tableNameB = resultB.resultName;
		String prefixA = tableNameA + ".";
		String prefixB = tableNameB + ".";
		Map<String, List<Object>> resultSetA = resultA.resultSet;
		Map<String, List<Object>> resultSetB = resultB.resultSet;
		Set<String> fieldA = resultSetA.keySet();
		Set<String> fieldB = resultSetB.keySet();
		for (String attr : fieldA) {
			if (fieldB.contains(attr)) {
				String s = prefixA + attr;
				List<Object> temp = new ArrayList<Object>();
					for (int j = 0; j < resultSetA.get(attr).size(); j++) 
						for (int i = 0; i < numberB; i++) {
							temp.add(resultSetA.get(attr).get(j));
				}
				resultSet.put(s, temp);
			}
			else {
				List<Object> temp = new ArrayList<Object>();
				for (int i = 0; i < numberB; i++) {
					temp.add(resultSetA.get(attr).get(i));
				}
				resultSet.put(attr, temp);
			}
		}
		for (String attr : fieldB) {
			if (fieldA.contains(attr)) {
				String s = prefixB + attr;
				List<Object> temp = new ArrayList<Object>();
				for (int i = 0; i < numberA; i++) {
					temp.addAll(resultSetB.get(attr));
				}
				resultSet.put(s, temp);
			}
			else {
				List<Object> temp = new ArrayList<Object>();
				for (int i = 0; i < numberA; i++) {
					temp.addAll(resultSetB.get(attr));
				}
				resultSet.put(attr, temp);
			}
		}

		return new ResultSet(resultSet);
	}

}
